﻿#include "transform.h"
#include <glm/gtx/matrix_transform_2d.hpp>
#include <algorithm>

using namespace anip;

mat3 Transform2D::toMatrix() const
{
	mat3 m = glm::mat3(1.0f);
	// first calling glm::translate here causes translation 
	// seem to be performed AFTER rotation and scaling, due
	// to matrix multiplication rules
	m = glm::translate(m, offset);
	m = glm::rotate(m, rotation);
	m = glm::scale(m, zoom);
	return m;
}

void anip::Transform2D::transformBoundingRect(outvec2 p, outvec2 s) const
{
	vec2 
		p1 = transform(p), 
		p2 = transform(p + vec2{ s.x, 0 }), 
		p3 = transform(p + vec2{ 0, s.y }), 
		p4 = transform(p + s);
	vec2
		o1{std::min({p1.x, p2.x, p3.x, p4.x}), std::min({p1.y, p2.y, p3.y, p4.y})},
		o2{std::max({p1.x, p2.x, p3.x, p4.x}), std::max({p1.y, p2.y, p3.y, p4.y})};
	p = o1;
	s = o2 - o1;
}

void anip::Transform2D::undoTransformBoundingRect(outvec2 p, outvec2 s) const
{
	vec2 
		p1 = undoTransform(p), 
		p2 = undoTransform(p + vec2{ s.x, 0 }), 
		p3 = undoTransform(p + vec2{ 0, s.y }), 
		p4 = undoTransform(p + s);
	vec2
		o1{std::min({p1.x, p2.x, p3.x, p4.x}), std::min({p1.y, p2.y, p3.y, p4.y})},
		o2{std::max({p1.x, p2.x, p3.x, p4.x}), std::max({p1.y, p2.y, p3.y, p4.y})};
	p = o1;
	s = o2 - o1;
}
